<template>
  <main-header style="z-index: 999;"></main-header>
  <div class="dataCenter-board-template">
    <!-- 顶部菜单 -->
    <div class="templateHeader">
      <div class="templateHeader-left">
        {{ currentMenuName }}
      </div>
      <div class="templateHeader-right">
        <el-form :inline="true" :model="form" class="demo-form-inline">
          <el-form-item label="看板:">
            <el-cascader
              v-model="form.menu"
              :options="menuOptions"
              :props="props"
              @change="handleChangeCascader"
            />
          </el-form-item>
          <el-form-item label="时间段:">
            <el-date-picker
              style="width: 260px;"
              v-model="form.date"
              type="daterange"
              value-format="YYYY-MM-DD"
              unlink-panels
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              :size="size"
              @change="handleChangeDate"
            />
          </el-form-item>
          <el-form-item label="机构:">
            <el-cascader
              v-model="form.organizationId"
              clearable
              :options="orgOptions"
              :props="props"
              @change="handleChangeOrganization" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleClickAppendChat">添加图表</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="List" @click="handleClickSave">保存更新排版</el-button>
          </el-form-item>
          <el-form-item>
            <el-dropdown @command="handleClickCreateMenu">
              <el-button type="primary">
                <!-- <el-icon><CirclePlus /></el-icon>&nbsp; -->
                新建(看板/分组)
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="1">新建看板</el-dropdown-item>
                  <el-dropdown-item :command="2">新建分组</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
          <el-form-item>
            <el-dropdown @command="handleClickEditMenu">
              <el-button type="primary">
                <el-icon><More /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="1">编辑看板</el-dropdown-item>
                  <el-dropdown-item divided :command="2">移动看板</el-dropdown-item>
                  <el-dropdown-item :command="3">删除看板</el-dropdown-item>
                  <!-- <el-dropdown-item divided :command="4">保存界面为PDF</el-dropdown-item> -->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 全部组件template -->
    <div class="templateComponents" v-if="templateList.length != 0">
      <draggable
        id="draggable"
        :component-data="{
          tag: 'div',
          type: 'transition-group',
        }"
        v-model="templateList"
        v-bind="dragOptions"
        @start="drag = true"
        @end="drag = false"
        item-key="id">
        <template #item="{ element }">
          <div 
            class="list-group-item" 
            :class="
              [
                element.layout === 'medium' ? 'medium' 
              : (element.layout === 'small' ? 'small' : 'mini'),
              element.largeHeight ? 'largeHeight' : ''
              ]
            ">
            <!-- 拖拽handle -->
            <div class="dragIcon">
              <img class="handle" :src="handleMove" alt="">
            </div>
            <!-- 操作opera -->
            <div class="operaIcon">
              <el-dropdown @command="handleCommand($event, element)">
                <img class="more" :src="handleMore" alt="">
                <template v-slot:dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">编辑</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                    <el-dropdown-item command="export">导出数据</el-dropdown-item>
                    <el-dropdown-item v-if="element.type === 'line' || element.type === 'lineTrend' || element.type === 'bar'" command="dataScreen">数据展示筛选</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <!-- 指标Component -->
            <Indicator
              v-if="element.type === 'indicator'"
              v-model:id="element.id">
            </Indicator>

            <!-- 折线图Component -->
            <LineChart
              v-if="element.type === 'line'"
              v-model:id="element.id">
            </LineChart>

            <!-- 指标卡趋势图Component -->
            <LineTrendChart
              v-if="element.type === 'lineTrend'"
              v-model:id="element.id">
            </LineTrendChart>

            <!-- 柱状图Component -->
            <BarChart
              v-if="element.type === 'bar'"
              v-model:id="element.id">
            </BarChart>

            <!-- 饼图Component -->
            <PieChart
              v-if="element.type === 'pie'"
              v-model:id="element.id">
            </PieChart>

            <!-- 排名Component -->
            <Ranking
              v-if="element.type === 'ranking'"
              v-model:id="element.id">
            </Ranking>

            <!-- 表格Component -->
            <CommonTable
              v-if="element.type === 'table'"
              v-model:id="element.id">
            </CommonTable>

            <!-- 漏斗图Component -->
            <FunnelChart
              v-if="element.type === 'funnel'"
              v-model:id="element.id">
            </FunnelChart>
          </div>
        </template>
      </draggable>
    </div>
    <!-- 无图表展示Icon -->
    <div class="templateComponents-else" v-else>
      <div class="empty">
        <p class="empty-img">
          <img class="img" :src="indexEmpty" alt="">
        </p>
        <p class="empty-text">
          您还未添加任何图表，快去添加图表吧
        </p>
        <p class="empty-btn">
          <el-button type="primary" @click="handleClickAppendChat">添加图表</el-button>
        </p>
      </div>
    </div>
    <!-- 添加图表Dialog -->
    <AppendChatDialog
      v-model:visible="appendChatVisible"
      v-model:id="chartId"
      @handleClickConfirm="handleClickConfirm">
    </AppendChatDialog>
    <!-- 动态导出多级表头excel -->
    <div class="templateComponents-table">
      <el-table
        id="outTable"
        ref="report-table"
        :data="tableData"
        style="width: 100%;height: 230px;"
        header-cell-class-name="headerCellClass">
        <template
          v-for="(item, index) in column"
          :key="index">
          <el-table-column
            :width="item.width?item.width:'auto'"
            :prop="item.prop"
            :align="item.align?item.align:'center'"
            :label="item.label">
            <template
              #default="scope"
              v-if="item.isNested?item.isNested:false">
              <el-table-column
                v-for="(value, key) in item.childrenColumn"
                :key="key"
                :width="value.width?value.width:'auto'"
                :prop="value.prop"
                :align="value.align?value.align:'center'"
                :label="value.label">
                <template #default="scope">
                  <slot v-if="value.slot" :name="value.prop" :row="scope.row"></slot>
                  <template v-else>
                    {{ scope.row[value.prop] }}
                  </template>
                </template>
              </el-table-column>
            </template>
            <template #default="scope" v-else>
              <slot v-if="item.slot" :name="item.prop" :row="scope.row"></slot>
              <template v-else>
                {{ scope.row[item.prop] }}
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <!-- 新建看板 -->
    <BoardDialog
      v-model:visible="boardVisible"
      v-model:id="boardId"
      v-model:organizationId="form.organizationId"
      @handleUpdateMenu="handleUpdateMenu">
    </BoardDialog>
    <!-- 新建分组 -->
    <GroupDialog
      v-model:visible="groupVisible"
      v-model:id="groupId"
      v-model:organizationId="form.organizationId"
      @handleUpdateMenu="handleUpdateMenu">
    </GroupDialog>
    <!-- 移动分组 -->
    <MobileBoardDialog
      v-model:visible="mobileBoardVisible"
      @handleUpdateMenu="handleUpdateMenu">
    </MobileBoardDialog>
  </div>
  
</template>

<script>
import MessageCenter from '@/components/messageCenter/index.vue'
// 基础
import draggable from "vuedraggable";
import AppendChatDialog from './component/appendChatDialog.vue';
import handleMove from '@/assets/dataCenter/dataBoard_move.png';
import handleMore from '@/assets/dataCenter/dataBoard_more.png';
import { ElMessage, ElMessageBox } from "element-plus";
import BoardDialog from './component/boardDialog.vue';
import GroupDialog from './component/groupDialog.vue';
import MobileBoardDialog from './component/mobileBoardDialog.vue';
// 组件
import Indicator from './component/indicator.vue';
import LineChart from './component/lineChart.vue';
import LineTrendChart from './component/lineTrendChart.vue';
import BarChart from './component/barChart.vue';
import PieChart from './component/pieChart.vue';
import Ranking from './component/ranking.vue';
import CommonTable from './component/commonTable.vue';
import FunnelChart from './component/funnelChart.vue';
// API
import {
  dataBoardByReportMenuId,
  dataBoardDeleteChartById,
  merchantInsQueryTree,
  dataBoardReserveChart,
  dataBoardReportMenuList,
  dataBoardReportMerReMenuInsById,
  merchantReportmenuRemoveSubMerMenu,
  
} from '@/api/dataCenter/dataBoard.js';
// vuex
import store from "@/store";
// xlsx
import FileSaver from 'file-saver';
import * as XLSX from "xlsx";
// API
import { dataBoardByChartId, dataBoardMerchantGetChatData } from '@/api/dataCenter/dataBoard.js';
import { dateStrChangeTimeTamp } from './component/utils.js';
// img
import indexEmpty from '@/assets/dataCenter/dataB_indexEmpty.png';
export default {
  name: "dataCenter-board-template",
  components: {
    draggable,
    AppendChatDialog,
    Indicator,
    LineChart,
    LineTrendChart,
    BarChart,
    PieChart,
    Ranking,
    CommonTable,
    FunnelChart,
    BoardDialog,
    GroupDialog,
    MobileBoardDialog,
    MessageCenter
  },
  data() {
    return {
      indexEmpty,
      boardVisible: false,
      boardId: null,
      groupVisible: false,
      groupId: null,
      mobileBoardVisible: false,
      currentMenuName: null,
      chartId: null,
      form: {
        menu: '',
        organizationId: '',
        date: []
      },
      filtrateDate: [],
      menuOptions: [],
      orgOptions: [],
      drag: false,
      appendChatVisible: false,
      handleMove,
      handleMore,
      options: [
        {
          value: '1',
          label: '整体分析'
        },
        {
          value: '2',
          label: '概览分析'
        },
      ],
      props: {
        value: 'id',
        label: 'name',
        children: 'children',
        expandTrigger: 'hover',
      },
      templateList: [
        // {
        //   id: 1,
        //   name: '指标',
        //   size: 'mini',
        //   type: 'indicator',
        //   largeHeight: false,
        //   data: {
        //     // 对应指标查询的具体数据
        //     // 例如 title time 
        //   }
        // },
        // {
        //   id: 1,
        //   name: '指标',
        //   size: 'small',
        //   type: 'line',
        //   largeHeight: false,
        //   data: {
        //     // 对应指标查询的具体数据
        //     // 例如 title time 
        //   }
        // },
        // {
        //   id: 1,
        //   name: '指标',
        //   size: 'small',
        //   type: 'bar',
        //   largeHeight: false,
        //   data: {
        //     // 对应指标查询的具体数据
        //     // 例如 title time 
        //   }
        // },
      ],
      size: '' | 'large' | 'small',
      shortcuts: [
        {
          text: '昨天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            return [start, end]
          },
        },
        {
          text: '过去7天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          },
        },
        {
          text: '过去14天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14)
            return [start, end]
          },
        },
        {
          text: '过去30天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          },
        },
        {
          text: '过去2个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 60)
            return [start, end]
          },
        },
        {
          text: '过去3个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          },
        },
        {
          text: '过去6个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            return [start, end]
          },
        },
        {
          text: '过去12个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            return [start, end]
          },
        },
      ],
      reportData: [],
      payloadData: null,
      tableData: [],
      column: []
    };
  },
  watch: {
    templateList: {
      handler(val) {
        
      },
      deep: true
    }
  },
  async mounted() {
    // 优先获取机构数据
    await this.merchantInsQueryTreeApi();
  },  
  methods: {
    // 新建菜单分组
    handleClickCreateMenu(val) {
      // 1 新建看板
      if(val === 1) {
        this.boardVisible = true;
        this.boardId = null;
      }
      // 2 新建分组
      if(val === 2) {
        this.groupVisible = true;
        this.groupId = null
      }
    },
    // 编辑菜单分组
    handleClickEditMenu(val) {
      // 1 编辑看板
      if(val === 1) {
        this.boardVisible = true;
        this.boardId = this.form.menu[1];
      }
      // 2 移动看板
      if(val === 2) {
        this.mobileBoardVisible = true;
      }
      // 3 删除看板
      if(val === 3) {
        ElMessageBox.confirm(`确认删除该看板吗？看板删除后,不可恢复！`, "删除提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.merchantReportmenuRemoveSubMerMenuApi();
        });
      }
      // 4 保存为PDF
      if(val === 4) {
        window.print();
      }
    },
    // 更新菜单
    async handleUpdateMenu(val) {
      let res = await dataBoardReportMerReMenuInsById({
        insId: this.form.organizationId,
        merchantId: store.state.user.merchantId,
        id: '1'
      });
      if(res.code === 200) {
        this.menuOptions = res.payload;
        // 遍历获取菜单name
        this.menuOptions.forEach(item => {
          if(item.children && item.children.length != 0) {
            item.children.forEach(value => {
              if(value.id === store.state.user.currentMenuId) {
                this.form.menu = [item.id, value.id];
                this.currentMenuName = value.name;
              }
            })
          }
        })
        // 置空操作ID
        this.boardId = null;
        this.groupId = null;
      }
    },
    // 删除看板Api
    async merchantReportmenuRemoveSubMerMenuApi() {
      let res = await merchantReportmenuRemoveSubMerMenu({
        id: this.form.menu[1]
      })
      if(res.code === 200) {
        ElMessage({
          type: "success",
          message: "删除看板成功",
        });
        // 默认菜单id 赋值vuex
        store.commit('SETCURRENTMENUID', null);
        // 获取菜单
        this.dataBoardReportMerReMenuInsByIdApi(this.form.organizationId, store.state.user.merchantId);
      }
    },
    // 选择时间段
    handleChangeDate(val) {
      // store.commit('SETSCREENTIME', []);
      store.commit('SETSCREENTIME', val);
    },
    // 选择机构节点
    handleChangeOrganization(val) {
      console.log(val);
      store.commit('SETORGANIZATIONID', val[0]);
    },
    // 获取机构树Api
    async merchantInsQueryTreeApi() {
      let res = await merchantInsQueryTree()
      if(res.code === 200) {
        this.orgOptions = res.payload
        // 判断是否已选机构节点
        if(store.state.insId.insId) {
          // 取值vuex
          this.form.organizationId = store.state.insId.insId;
        } else {
          // 默认机构值val
          this.form.organizationId = this.orgOptions[0].id;
          // 更新vuex
          store.commit('SETORGANIZATIONID', this.form.organizationId);
        }
        // 获取菜单
        this.dataBoardReportMerReMenuInsByIdApi(this.form.organizationId, store.state.user.merchantId);
        // this.dataBoardReportMenuListApi(store.state.user.merchantId);
        // 默认筛选时间
        if(store.state.user.screenTime && store.state.user.screenTime.length != 0) {
          this.form.date = store.state.user.screenTime;
        }
      }
    },
    // 获取菜单下所有图表数据Api
    async dataBoardByReportMenuIdApi(id) {
      let res = await dataBoardByReportMenuId({
        id,
        insId: this.form.organizationId
      });
      if(res.code === 200) {
        this.templateList = res.payload;
        this.templateList.forEach(item => {
          if(item.type === 'lineTrend') {
            item.largeHeight = true;
          }
        })
      } else {
        this.templateList = [];
      }
    },
    // 新增图表
    handleClickAppendChat() {
      this.chartId = null;
      this.appendChatVisible = true;
      console.log(this.templateList);
    },
    // item操作
    handleCommand(command, item) {
      console.log(item, 'handleCommand');
      if(command === 'edit') {
        this.chartId = item.id;
        this.appendChatVisible = true;
      } else if(command === 'del') {
        ElMessageBox.confirm(`确认删除该报表吗？`, "删除提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.dataBoardDeleteChartByIdApi(item.id);
        });
      } else if(command === 'export') {
        // 下载
        this.dataBoardChartExportApi(item.id);
      } else {
        // 先置空
        store.commit('OPENDATASCREEN', null);
        // 数据展示筛选
        store.commit('OPENDATASCREEN', item.id);
      }
    },
    // 级联选择菜单
    handleChangeCascader(val) {
      if(val.length != 2) {
        ElMessage({
          type: "warning",
          message: "该分组下没有看板,请新增看板",
        });
        return false;
      }
      // 切换菜单更新vuex
      store.commit('SETCURRENTMENUID', val[1]);
      this.dataBoardByReportMenuIdApi(val[1]);
      // 遍历获取菜单name
      this.menuOptions.forEach(item => {
        if(item.children && item.children.length != 0) {
          item.children.forEach(value => {
            if(value.id === val[1]) {
              this.currentMenuName = value.name;
            }
          })
        }
      })
    },
    // 根据商户ID获取菜单列表Api(弃用)
    // async dataBoardReportMenuListApi(id) {
    //   let res = await dataBoardReportMenuList({
    //     id
    //   });
    //   if(res.code === 200) {
    //     this.menuOptions = res.payload;
    //     this.dataBoardByReportMenuIdApi(this.menuOptions[0].children[0].id);
    //     // 默认菜单id 赋值vuex
    //     store.commit('SETCURRENTMENUID', this.menuOptions[0].children[0].id);
    //     // 默认菜单val
    //     this.form.menu = [this.menuOptions[0].id, this.menuOptions[0].children[0].id];
    //     this.currentMenuName = this.menuOptions[0].children[0].name;
    //   }
    // },
    // 根据机构id获取菜单列表Api
    async dataBoardReportMerReMenuInsByIdApi(insId, merchantId) {
      let res = await dataBoardReportMerReMenuInsById({
        insId,
        merchantId,
        id: '1'
      });
      if(res.code === 200) {
        this.menuOptions = res.payload;
        if(store.state.user.currentMenuId) {
          console.log('enter you', this.menuOptions, store.state.user.currentMenuId)
          let currentMenuId = store.state.user.currentMenuId;
          this.dataBoardByReportMenuIdApi(currentMenuId);
          // 默认菜单val
          this.menuOptions.forEach(item => {
            if(item.children && item.children.length != 0) {
              item.children.forEach(value => {
                if(currentMenuId === value.id) {
                  this.form.menu = [item.id, value.id];
                  this.currentMenuName = value.name;
                }
              })
            }
          })
          console.log('this.form.menu', this.form.menu)
        } else {
          console.log('enter wu', this.menuOptions)
          let currentMenuId = null;
          let isStop = false;
          this.menuOptions.forEach(item => {
            if(item.children && item.children.length != 0 && !isStop) {
              currentMenuId = item.children[0].id
              this.dataBoardByReportMenuIdApi(currentMenuId);
              // 默认菜单id 赋值vuex
              store.commit('SETCURRENTMENUID', currentMenuId);
              // 默认菜单val
              this.form.menu = [item.id, currentMenuId];
              this.currentMenuName = item.children[0].name;
              isStop = true;
            }
          })
        }
      }
    },
    // 新增图表
    handleClickConfirm(val, isEdit) {
      let obj = JSON.parse(JSON.stringify(val));
      if(obj.type === 'lineTrend') {
        obj.largeHeight = true;
      }
      console.log(isEdit)
      // 编辑
      if(isEdit) {
        this.templateList.forEach((item, index) => {
          if(item.id === val.id) {
            this.templateList.splice(index, 1, obj);
            // 先设置假的 100毫秒后换回真的
            this.templateList[index].type = null;
            setTimeout(() => {
              this.templateList[index].type = val.type;
            }, 100)
          }
        })
      } else {
        this.templateList.unshift(obj);
      }
      console.log('this.templateList',this.templateList)
    },
    // 删除图表Api
    async dataBoardDeleteChartByIdApi(id) {
      let res = await dataBoardDeleteChartById({
        id
      });
      if(res.code === 200) {
        this.templateList.forEach((item, index) => {
          if(item.id === id) {
            this.templateList.splice(index, 1);
          }
        });
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      }
    },
    handleClickSave() {
      this.dataBoardReserveChartApi();
    },
    // 保存更新图标位置
    async dataBoardReserveChartApi() {
      this.templateList.forEach((item, index) => {
        item.sort = index + 1;
      })
      let res = await dataBoardReserveChart(this.templateList);
      if(res.code === 200) {
        ElMessage({
          type: "success",
          message: "更新排版成功",
        });
      }
    },
    // 下载导出
    dataBoardChartExportApi(id) {
      this.dataBoardByChartIdApi(id);
    },
    // 获取DATA1
    async dataBoardByChartIdApi(id) {
      let res = await dataBoardByChartId({
        id
      });
      if(res.code === 200) {
        this.reportData = res.payload;
        // 获取Excel数据
        this.dataBoardMerchantGetChatDataApi(id);
      }
    },
    // 获取DATA2
    async dataBoardMerchantGetChatDataApi(id) {
      let startTime;
      let endTime;
      let screenTime = store.state.user.screenTime;
      if(screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      } else {
        // startTime 和 endTime存在即固定时间
        if(this.reportData.startTime && this.reportData.endTime) {
          startTime = this.reportData.startTime;
          endTime = this.reportData.endTime;
        }
        // relativelyTime存在即相对时间
        if(this.reportData.relativelyTime) {
          let nowDate = new Date().getTime();
          let startDate = nowDate - this.reportData.relativelyTime;
          startTime = startDate;
          endTime = nowDate;
        }
      }
      let res = await dataBoardMerchantGetChatData({
        id,
        startTime,
        endTime,
        insId: store.state.insId.insId,
        currentPage: 1,
        showCount: 99999
      })
      if(res.code === 200) {
        this.payloadData = res.payload;
        this.capsulationDealData(this.payloadData.chartName, this.payloadData.startTime, this.payloadData.endTime);
      }
    },
    // 处理数据封装
    capsulationDealData(nameVal, sTimeVal, eTimeVal) {
      var column = [];
      var tableData = [];
      // 1、区分分组和不分组情况
      if(this.payloadData.groupColumn && this.payloadData.groupColumn.indexOf('columnHumpName') != -1) {
      // 1.1分组逻辑
        let specialColumn = [];
        let indicatorsColumn = ''; // 分组表格首个表头
        let columnHumpName = ''; // 获取数据存储字段
        let groupColumn = JSON.parse(this.payloadData.groupColumn.replace(/\\/g, ''));
        indicatorsColumn = groupColumn[0].columnDesc;
        columnHumpName = groupColumn[0].columnHumpName;

        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') != -1) { // 多指标
          // 处理表头
          let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
          dealSpecialColumn.forEach(item => {
            let obj = {};
            obj.enVal = item.split('=')[0];
            obj.chnVal = item.split('=')[1];
            specialColumn.push(obj);
          })
          console.log(specialColumn, 'specialColumn')
          column = [
            {
              prop: 'totalColumn',
              align: '',
              label: indicatorsColumn,
              scopeStatus:false,
              width:"",
            },
            {
              align: '',
              label: '合计',
              scopeStatus:false,
              width:"",
              isNested: true,
              childrenColumn: []
            }
          ];
          // 处理合计列表头
          specialColumn.forEach(item => {
            let obj = {
              prop: '',
              align: '',
              label: '',
              scopeStatus:false,
              width:"",
            }
            obj.prop = item.enVal;
            obj.label = item.chnVal;
            column[1].childrenColumn.push(obj);
          })
          console.log('column', column);

          // 处理具体数据
          let dayData = [];
          dayData = JSON.parse(JSON.stringify(this.payloadData.dayData));
          dayData.forEach(item => {
            item.time = new Date(item.createTime).format("yyyy-MM-dd");
            item.dayData = JSON.parse(item.dayData.replace(/\\/g, ''));
          })
          console.log('dayData', dayData)
          // 提取第一列
          let tableDataStep1 = [];
          dayData.forEach((item, index) => {
            if(index === 0) {
              item.dayData.forEach(val => {
                let obj = {};
                for(let i in val) {
                  if(String(columnHumpName) === String(i)) {
                    obj['totalColumn'] = val[i];
                  } else {
                    obj[i] = 0;
                  }
                }
                tableDataStep1.push(obj);
              })
            }
          })
          dayData.forEach(item => {
            item.time = new Date(item.createTime).format("yyyy-MM-dd");
            item.dayData.forEach(val1 => {
              tableDataStep1.forEach(val2 => {
                if(val1[columnHumpName] === val2.totalColumn) {
                  for(let i in val1) {
                    for(let j in val2) {
                      if(i === j) {
                        val2[j] += Number(val1[i]);
                      }
                    }
                  }
                } 
              })
            })
          })

          dayData.forEach(item => {
            item.dayData.forEach(val1 => {
              tableDataStep1.forEach(val2 => {
                if(val1[columnHumpName] === val2.totalColumn) {
                  for(let i in val1) {
                    for(let j in val2) {
                      if(i === j) {
                        val2[i + item.time] = val1[i];
                      }
                    }
                  }
                } 
              })
            })
          })
          console.log('tableDataStep1', tableDataStep1)
          tableData = tableDataStep1;

          // 处理剩余日期表头
          dayData.forEach(item => {
            let obj1 = {
              align: '',
              label: item.time,
              scopeStatus:false,
              width:"",
              isNested: true,
              childrenColumn: []
            }
            specialColumn.forEach(val1 => {
              let obj2 = {
                prop: '',
                align: '',
                label: '',
                scopeStatus:false,
                width:"",
              }
              item.dayData.forEach(val2 => {
                for(let i in val2) {
                  if(i === val1.enVal) {
                    obj2.prop = val1.enVal + item.time;
                    obj2.label = val1.chnVal;
                  }
                }
              })
              obj1.childrenColumn.push(obj2)
            })
            column.push(obj1)
          })
          console.log('column', column)
        } else { // 单指标
          // 处理表头
          specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=')[0];
          column = [
            {
              prop: columnHumpName,
              align: '',
              label: indicatorsColumn,
              scopeStatus:false,
              width:"",
            },
            {
              prop: 'totalColumn',
              align: '',
              label: '合计',
              scopeStatus:false,
              width:"",
            }
          ];
          this.payloadData.dayData.forEach(item => {
            let obj = {
              prop: new Date(item.createTime).format("yyyy-MM-dd"),
              align: '',
              label: new Date(item.createTime).format("yyyy-MM-dd"),
              scopeStatus:false,
              width:"",
            }
            column.push(obj);
          })

          // 处理数据
          let dayData = [];
          dayData = JSON.parse(JSON.stringify(this.payloadData.dayData));
          dayData.forEach(item => {
            item.time = new Date(item.createTime).format("yyyy-MM-dd");
            item.dayData = JSON.parse(item.dayData.replace(/\\/g, ''));
          })
          console.log('dayData', dayData)
          // 提取每个日期对应的数据
          let tableDataStep1 = [];
          dayData.forEach(item => {
            item.dayData.forEach(val => {
              let obj = {
                time: item.time,
              }
              for(let i in val) {
                if(String(specialColumn) === String(i)) {
                  obj[i] = val[i]
                }
                if(String(columnHumpName) === String(i)) {
                  obj[i] = val[i]
                }
              }
              tableDataStep1.push(obj);
            })
          })
          console.log('tableDataStep1', tableDataStep1)
          // 计算整合合计数据
          let tableDataStep2 = [];
          let arr = [];
          tableDataStep1.forEach(item => {
            for(let i in item) {
              if(String(columnHumpName) === String(i)) {
                arr.push(item[i]);
              }
            }
          })
          arr = Array.from(new Set(arr));
          console.log('arr', arr)
          arr.forEach(item => {
            let num = 0;
            tableDataStep1.forEach(val => {
              for(let i in val) {
                if(val[i] === item) {
                  num += Number(val[specialColumn])
                }
              }
            })
            let obj = {}
            obj[columnHumpName] = item;
            obj.totalColumn = num;
            tableDataStep2.push(obj);
          })
          console.log('tableDataStep2', tableDataStep2)
          // 整合统计和日期数据
          tableDataStep2.forEach(item => {
            tableDataStep1.forEach(val => {
              if(item[columnHumpName] === val[columnHumpName]) {
                item[val.time] = val[specialColumn]
              }
            })
          })
          tableData = tableDataStep2;
        }
      } else {
      // 1.2不分组逻辑
        let specialColumn = [];
        // 具体数值字段获取
        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') != -1) {
          // 多指标
          let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
          dealSpecialColumn.forEach(item => {
            let obj = {};
            obj.enVal = item.split('=')[0];
            obj.chnVal = item.split('=')[1];
            specialColumn.push(obj);
          })
          column = [
            {
              prop: 'date',
              align: '',
              label: '日期',
              scopeStatus:false,
              width:"",
            }
          ]
          specialColumn.forEach(item => {
            let obj = {
              prop: item.enVal,
              align: '',
              label: item.chnVal,
              scopeStatus:false,
              width:"",
            }
            column.push(obj);
          })
        } else {
          // 单指标
          specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=');
          column = [
            {
              prop: 'date',
              align: '',
              label: '日期',
              scopeStatus:false,
              width:"",
            }
          ];
          let obj = {
            prop: specialColumn[0],
            align: '',
            label: specialColumn[1],
            scopeStatus:false,
            width:"",
          }
          column.push(obj);
        }
        // 处理具体数据
        // Step1
        let chartData = [];
        this.payloadData.dayData.forEach(item => {
          let obj = {};
          obj.date = new Date(item.createTime).format("yyyy-MM-dd");
          obj.id = item.id
          obj.insId = item.insId
          obj.reportId = item.reportId
          obj.value = JSON.parse(item.dayData.replace(/\\/g, ''));
          let objVal = Object.assign({}, obj, obj.value[0]);
          chartData.push(objVal);
        });
        // 合计
        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') != -1) {
          console.log('enter 多指标不分组')
          // 多指标
          let totalArr = [];
          specialColumn.forEach((item, index) => {
            let totalObj = {
              num: 0,
              enVal: ''
            }
            chartData.forEach((val, key) => {
              for(let i in val) {
                if(String(item.enVal) === String(i)) {
                  totalObj.enVal = item.enVal;
                  totalObj.num += Number(val[i]);
                }
              }
            })
            totalArr.push(totalObj);
          })
          tableData = JSON.parse(JSON.stringify(chartData));
          tableData.unshift(chartData[chartData.length -1]);
          console.log('tableData', tableData)
          tableData.forEach((item, index) => {
            if(index === 0) {
              item.date = '合计'
              totalArr.forEach(val => {
                for(let i in item) {
                  if(val.enVal === String(i)) {
                    item[i] = val.num;
                  }
                }
              })
            }
          })
        } else {
          console.log('enter 单指标不分组', specialColumn)
          // 单指标
          let totalNum = 0;
          chartData.forEach(item => {
            for(let i in item) {
              if(String(specialColumn[0]) === String(i)) {
                totalNum += Number(item[i]);
              }
            }
          })
          tableData = JSON.parse(JSON.stringify(chartData));
          tableData.unshift(chartData[chartData.length -1]);
          tableData.forEach((item, index) => {
            if(index === 0) {
              item.date = '合计'
              for(let i in item) {
                if(String(specialColumn[0]) === String(i)) {
                  item[i] = totalNum;
                }
              }
            }
          })
        }
      }
      console.log('tableData', tableData)
      console.log('column', column)
      this.tableData = tableData;
      this.column = column;
      let excelName = '';
      excelName = nameVal + '(' + new Date(sTimeVal).format("yyyy-MM-dd") + '至' + new Date(eTimeVal).format("yyyy-MM-dd") + ')';
      this.$nextTick(() => {
        this.exportExcel(excelName);
      })
    },
    // 导出excel
    exportExcel(excelName) {
      try {
        const $e = this.$refs['report-table'].$el
        let $table = $e.querySelector('.el-table__fixed')
        if(!$table) {
          $table = $e
        }
        const wb = XLSX.utils.table_to_book($table, {raw:true})
        const wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST:true, type: 'array'})
        FileSaver.saveAs(
          new Blob([wbout],{type: 'application/octet-stream'}),
          `${excelName}.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 200,
        group: "",
        disabled: false,
        ghostClass: "ghost",
        handle: '.handle'
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.dataCenter-board-template {
  width: 100%;
  height: 100%;
  position: relative;
  background: #f7f8fa;
  padding-top: 60px;
  :deep(.icon-arrow-down:before) {
    display: none;
  }
  .templateHeader {
    z-index: 9999;
    width: 100%;
    // height: 56px;
    padding: 14px 4px;
    background: #fff;
    box-sizing: border-box;
    margin: 0 0 0.5% 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    &-left {
      font-size: 18px;
      color: #252934;
      font-weight: 600;
      min-width: 200px;
    }
    &-right {
      min-width: 1220px;
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    :deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 4px;
    }
    :deep(.el-form-item__label) {
      font-weight: 600;
    }
  }
  .templateComponents {
    width: 100%;
    height: 100%;
    // background: pink;
    #draggable {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      flex-wrap: wrap;
      .list-group-item {
        height: 380px;
        padding: 20px;
        background: #fff;
        box-sizing: border-box;
        position: relative;
        &:hover {
          box-shadow: 0 0 16px 2px rgb(0 31 86 / 10%);
        }
        .dragIcon {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 20px;
          display: flex;
          justify-content: center;
          align-items: center;
          .handle {
            display: none;
          }
        }
        &:hover .dragIcon .handle {
          display: block;
          cursor: pointer;
        }
        .operaIcon {
          position: absolute;
          top: 20px;
          right: 20px;
          display: none;
          z-index: 990;
        }
        &:hover .operaIcon {
          display: block;
        }
      }
      .medium {
        width: 99%;
        margin: 0.5%;
      }
      .small {
        width: 49%;
        margin: 0.5%;
      }
      .mini {
        width: 24%;
        margin: 0.5%;
        height: 182px;
      }
      .largeHeight {
        height: 538px;
      }
    }
  }
  .templateComponents-else {
    width: 100%;
    height: 700px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    .empty {
      width: 240px;
      height: 254px;
      &-img {
        width: 100%;
        height: 160px;
        text-align: center;
        .img {
          width: 160px;
          height: 100%;
        }
      }
      &-text {
        width: 100%;
        height: 20px;
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #909399;
        text-align: center;
        line-height: 20px;
        margin: 20px 0;
      }
      &-btn {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  .templateComponents-table {
    width: 0;
    height: 0;
  }
}
</style>